import time
import functions
from selenium.webdriver.common.by import By
from selenium.common.exceptions import InvalidArgumentException, WebDriverException, TimeoutException
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


# todo 基础类,封装了selenium基础方法,供page包下面的类继承
class Base:
    # 打开不同的浏览器
    def __init__(self, driver):
        self.driver = driver

    # 访问网址
    def get(self, url):
        # 如果网址不完整或者不存在，则捕获异常
        # selenium.common.exceptions.InvalidArgumentException: Message: invalid argument
        # selenium.common.exceptions.WebDriverException: Message: unknown
        try:
            self.driver.get(url)
        except (WebDriverException, InvalidArgumentException):
            print('请输入正确的网址')

    # 定位元素, locator = (By.XXX, ''), By.ID = 'id', By.NAME = 'name'...
    def find_element(self, locator, timeout=10):
        try:
            # return self.driver.find_element(*locator)  # locator为元组，*locator 拆包元组
            return WebDriverWait(self.driver, timeout).until(EC.presence_of_element_located(locator), '定位失败')
        except TimeoutException:
            print('找不到该元素')

    # 输入内容
    def send_keys(self, locator, keys_word):
        # 定位元素, 调用find_element方法
        element = self.find_element(locator)
        if element:
            element.send_keys(keys_word)

    # 点击click
    def click(self, locator):
        # 定位，调用find_element方法（函数）
        element = self.find_element(locator)
        if element:
            element.click()

    # 获取元素属性
    def get_attribute(self, value, locator):
        # 定位元素，调用find_element()方法（函数）
        element = self.find_element(locator)
        # 元素属性
        if element:
            element.get_attribute(value)

    # 获取标签文本
    def get_text(self, locator):
        element = self.find_element(locator)
        if element:
            return element.text

    # 页面刷新
    def refresh(self):
        self.driver.refresh()

    # 页面后退
    def back(self):
        self.driver.back()

    # 页面前进
    def forward(self):
        self.driver.forward()

    # 退出浏览器
    def quit(self, seconds=3):
        time.sleep(seconds)
        self.driver.quit()


if __name__ == '__main__':
    driver = functions.open_browser()
    b = Base(driver)
    b.get('https://www.baidu.com')
    # b.find_element((By.LINK_TEXT, '新闻'))
    # b.send_keys(('id', 'kw'), '天气')
    # b.click(('id', 'su'))
    # b.refresh()
    # b.back()
    # b.forward()
    # b.get_attribute('id', (By.NAME, 'wd'))
    b.get_text(('link text', '新闻'))
    b.quit()
